import type { InputProps } from 'element-plus'
import { onMounted, reactive, toRef, toRefs } from 'vue'

import { deptApi, dictApi, type IDeptListItem } from '@/apis'
import {
  type GridExtOptions,
  TABLE_FORMAT,
  TABLE_ITEM_RENDER,
  TABLE_RENDERER,
  useGridExt
} from '@/hooks'
import { dictToOptions, getElementFnFromInstance } from '@/utils'

import type { DeptDialogRef } from '../components'

export function useGrid() {
  const state = reactive({
    gridConfig: {
      loading: false,
      showOverflow: true,
      align: 'center',
      toolbarConfig: {
        custom: true,
        refresh: true,
        zoom: true,
        slots: {
          buttons: 'toolbar_buttons'
        }
      },
      formConfig: {
        items: [
          {
            field: 'deptName',
            title: '部门名称',
            itemRender: {
              name: TABLE_ITEM_RENDER.Input,
              props: {
                placeholder: '请输入'
              } as InputProps
            }
          },
          {
            field: 'status',
            title: '状态',
            itemRender: {
              name: TABLE_ITEM_RENDER.Select,
              props: {
                placeholder: '请选择'
              } as SelectProps
            }
          },
          {
            itemRender: {
              name: TABLE_RENDERER.FormItemBtns
            }
          }
        ]
      },
      columnConfig: {
        minWidth: 220
      },
      columns: [
        {
          field: 'deptName',
          title: '部门名称',
          treeNode: true,
          align: 'left'
        },
        {
          field: 'orderNum',
          title: '排序'
        },
        {
          field: 'status',
          title: '状态',
          slots: {
            default: 'columns_status'
          }
        },
        {
          field: 'createTime',
          title: '创建时间',
          formatter: TABLE_FORMAT.Date
        },
        {
          title: '操作',
          width: 140,
          fixed: 'right',
          className: 'columns_operation',
          slots: {
            default: 'columns_operation'
          }
        }
      ],
      proxyConfig: {
        seq: true,
        form: true,
        props: {
          result: 'list',
          total: 'total'
        },
        ajax: {
          query: async ({ form }) => {
            const data = await deptApi.getDeptList({
              ...form
            })
            return data
          }
        }
      },
      treeConfig: {
        transform: true,
        rowField: 'id',
        parentField: 'parentId',
        expandAll: true
      }
    } as GridExtOptions,
    statusOptions: [] as OptionItem[],
    deptDialogRef: {} as DeptDialogRef
  })

  const gridExtHook = useGridExt(toRef(state, 'gridConfig'))
  const { $msgbox } = getElementFnFromInstance()

  /**
   * 初始化
   */
  async function init() {
    const [dictStatus] = await Promise.all([
      dictApi.getDictDataList('sys_normal_disable')
    ])

    state.statusOptions = dictToOptions(dictStatus)

    gridExtHook.updateFormItem({
      field: 'status',
      key: 'itemRender.options',
      value: state.statusOptions
    })
  }

  /**
   * 显示新增
   */
  function handleShowAdd(parentId?: string) {
    if (parentId) {
      state.deptDialogRef.open({ parentId })
    } else {
      state.deptDialogRef.open()
    }
  }

  /**
   * 显示编辑
   */
  function handleShowEdit(item: IDeptListItem) {
    state.deptDialogRef.open(item, false)
  }

  /**
   * 切换展开
   */
  function handleToggleExpand() {
    const treeExpandRecords = gridExtHook.gridRef.value.getTreeExpandRecords()

    treeExpandRecords.length > 0
      ? gridExtHook.gridRef.value?.clearTreeExpand()
      : gridExtHook.gridRef.value?.setAllTreeExpand(true)
  }

  /**
   * 删除
   */
  function handleDelete(id: string) {
    $msgbox.confirm('确认删除？', '提示').then(async () => {
      await deptApi.deleteDept({
        ids: [id]
      })

      handleRefresh()
    })
  }

  /**
   * 刷新
   */
  async function handleRefresh() {
    await gridExtHook.refresh()
    gridExtHook.gridRef.value?.setAllTreeExpand(true)
  }

  onMounted(() => {
    init()
  })

  return {
    ...toRefs(state),
    gridExtHook,
    handleShowAdd,
    handleShowEdit,
    handleToggleExpand,
    handleDelete,
    handleRefresh
  }
}
